package com.corgi.multi.anno.config;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * @类名：         <p>LoadBalance</p>
 * @功能描述： <p>mysql服务器节点负载均衡算法</p>
 * @作者信息： <p>dengmiao</p>
 * @创建时间： <p>2018年5月7日上午9:51:21</p>
 * @修改备注：
 */
public class LoadBalance {

	/**
	 * @Title: RandomNode   
	 * @Description: 随机负载均衡算法 
	 * @param serverMap<key=mysql连接池标识,value=权重>
	 * @return
	 */
	public static String RandomNode(Map<String,Integer> serverMap){
		//获取ip列表list
		Set<String> keySet = serverMap.keySet();
		ArrayList<String> keyList = new ArrayList<String>();
		keyList.addAll(keySet);

		Random random = new Random();
		int randomPos = random.nextInt(keyList.size());

		String server = keyList.get(randomPos);
		return server;
	}
	
	/**
	 * @Title: WeightRandom   
	 * @Description: 加权随机负载均衡算法 
	 * @param serverMap<key=mysql连接池标识,value=权重>
	 * @return
	 */
	public static String WeightRandom(Map<String,Integer> serverMap){
		Set<String> keySet = serverMap.keySet();
		Iterator<String> it = keySet.iterator();

		List<String> serverList = new ArrayList<String>();

		while (it.hasNext()) {
			String server = it.next();
			Integer weight = serverMap.get(server);
			for (int i = 0; i < weight; i++) {
				serverList.add(server);
			}
		}        
		Random random = new Random();
		int randomPos = random.nextInt(serverList.size());

		String server = serverList.get(randomPos);
		return server;
	}
}
